package com.runmonk.core.study.concurrent.waitAndNotify_test;

import java.util.ArrayList;
import java.util.List;

public class Producer implements Runnable {
    private List<Integer> taskQueue = new ArrayList<Integer>();

    //生产的量
    private final int MAX_CAPACITY;

    //生产者构造器
    public Producer(List<Integer> sharedQueue, int size) {
        this.taskQueue = sharedQueue;
        this.MAX_CAPACITY = size;
    }

    @Override
    public void run() {
        int counter = 1;
        while (true) {
            try {
                synchronized (taskQueue) {
                    while (taskQueue.size() == MAX_CAPACITY) {
                        System.out.println("Queue is full " + Thread.currentThread().getName() + " is waiting , size: " + taskQueue.size());
                        taskQueue.wait();
                    }
                    Thread.sleep(100);
                    taskQueue.add(counter);
                    System.out.println("Produced 获取锁资源开始生产------>>>: " + counter);
                    counter++;
                    //唤醒正在等待的消费者，但是消费者是不是能获取到资源，由系统调度。
                    taskQueue.notify();
                }
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }

}
